#include "BlockFileHandler.h"
#include <FS.h>
#include "Common.h"

/**
 * @brief 读取配置
 * @param fileName 文件名
 * @param buff     配置项数组
 * @param len      数组长度
 * @return 读取是否成功
 */
bool BlockFileHandler::read(String fileName, String *buff, int len)
{
    int rLen = 0;
    int size = 0;

    if (SPIFFS.exists(fileName) == false)
        return false;

    File file = SPIFFS.open(fileName, "r");
    if (!file)
        return false;

    size = file.size();

    for (int x=0; x<len; x++) {
        if (file.position() >= size) {
            return false;
        }

        buff[x] = file.readStringUntil('\n');
        
        rLen = buff[x].length();
        if (buff[x][rLen-1] == '\r' || buff[x][rLen-1] == '\n') {
            buff[x][rLen-1] = '\0';
        }
    }
    
    LOG("Read items success!");
    file.close();
    return true;
}

/**
 * @brief 写入配置
 * @param fileName 文件名 
 * @param buff     配置项数组
 * @param len      数组长度
 * @return 写入是否成功
 */
bool BlockFileHandler::write(String fileName, String *buff, int len)
{
    File file = SPIFFS.open(fileName, "w");
    if (!file)
        return false;

    for (int x=0; x<len; x++) {
        file.println(buff[x]);
    }

    LOG("Write items success");
    file.close();
    return true;
}
